package com.pai4j.connect.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


/**
 * Redis健康检查服务
 * 提供Redis连接状态监控和降级策略
 *
 * @author: CYM-pai
 * @date: 2025/08/27 23:47
 **/
@Slf4j
@Service
public class RedisHealthService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private volatile boolean redisAvailable = true;
    private long lastCheckTime = 0;
    private static final long CHECK_INTERVAL = 30000; // 30秒检查一次

    /**
     * 检查Redis连接状态
     *
     * @return true表示Redis可用，false表示不可用
     */
    public boolean isRedisAvailable() {
        long currentTime = System.currentTimeMillis();
        if (currentTime - lastCheckTime > CHECK_INTERVAL) {
            checkRedisHealth();
            lastCheckTime = currentTime;
        }
        return redisAvailable;
    }

    /**
     * 执行Redis健康检查
     */
    private void checkRedisHealth() {
        try {
            // 使用ping命令检查Redis连接
            String result = redisTemplate.getConnectionFactory().getConnection().ping();
            redisAvailable = "PONG".equals(result);
            if (redisAvailable) {
                log.debug("Redis health check passed");
            } else {
                log.warn("Redis health check failed: unexpected ping response: {}", result);
            }
        } catch (Exception e) {
            redisAvailable = false;
            log.error("Redis health check failed: {}", e.getMessage());
        }
    }

    /**
     * 强制刷新Redis健康状态
     */
    public void refreshHealthStatus() {
        checkRedisHealth();
        lastCheckTime = System.currentTimeMillis();
    }

    /**
     * 获取Redis连接超时时间（毫秒）
     *
     * @return 超时时间
     */
    public long getConnectionTimeout() {
        return 10000; // 10秒超时
    }
}
